//
//  TestCollectionPageFlowTableViewCell_1.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2022/3/2.
//  Copyright © 2022 moon. All rights reserved.
//

#import "TestCollectionPageFlowTableViewCell_1.h"
#import "BGRefreshViewController.h"
@interface TestCollectionPageFlowTableViewCell_1()<MKUICollectionViewDelegatePageFlowLayout>
@property(nonatomic,strong) TestFunButton *pagingButton;
@end

@implementation TestCollectionPageFlowTableViewCell_1
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.opertaionView = [[TestOperationView alloc] init];
        self.opertaionView.addButton.hidden = YES;
        
        [self.opertaionView.preButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            [self.pageFlowLayout setIndexPathAtPagingCellWithDistance:-1 animated:YES];
        } context:self];
        [self.opertaionView.nextButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            [self.pageFlowLayout setIndexPathAtPagingCellWithDistance:+1 animated:YES];
        } context:self];
        [self.opertaionView.leftButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            self.scrollStep--;
            [self __refreshOperationView];
        } context:self];
        [self.opertaionView.rightButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            self.scrollStep++;
            [self __refreshOperationView];
        } context:self];
        [self.opertaionView.cycleButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            BOOL enableCycle = ![self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
            self.cellModel[@"enableCycle"] = @(enableCycle);
            [self __refreshGripLayout];
            [self __refreshOperationView];
            [self.pageFlowLayout invalidateLayout];
        } context:self];
        [self.opertaionView.refreshButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            [self.collectionView reloadData];
        } context:self];
        [self.opertaionView.refreshBgButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            NSIndexPath *indexpath = [self.pageFlowLayout indexPathAtPagingCell];
            if(indexpath){
                BGRefreshViewController *vc = [[BGRefreshViewController alloc] init];
                [vc view];
                [self.mk_viewControllerOfFirst.navigationController pushViewController:vc animated:YES];
                [vc.refreshButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
                    
                    [self.collectionView.model removeAllSectionModels];
                    [self.collectionView.model addCellModel:[self gemAddMenuCM]];
                    [self.collectionView.model reloadCollectionViewData];
                    [self.pageFlowLayout reloadData];
                    [self __refreshGripLayout];
                    [self __refreshPageControl];
                    [self __refreshOperationView];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.mk_viewControllerOfFirst.navigationController popViewControllerAnimated:YES];
                    });
                } context:self];
            }
        } context:self];
        
        TestFunButton *pagingButton = [[TestFunButton alloc] initWithTitle:@"UnPaging"];
        [pagingButton setTitle:@"Paging" forState:UIControlStateSelected];
        self.pagingButton = pagingButton;
        [pagingButton mk_addClickActionBlock:^(TestCollectionPageFlowTableViewCell_1 *self) {
            BOOL pagingEnabled = ![self.cellModel mk_boolForKeyPath:@"pagingEnabled" otherwise:YES];
            self.cellModel[@"pagingEnabled"] = @(pagingEnabled);
            [self __refreshGripLayout];
            [self __refreshOperationView];
            [self.pageFlowLayout invalidateLayout];
        } context:self];
        [self.opertaionView addSubview:pagingButton];
        [self.opertaionView.line2ayout addItem:pagingButton];
        
        [self.contentView addSubview:self.opertaionView];
        //
        //
        self.pageFlowLayout = [[[self.class pageFlowLayoutClass] alloc] init];
        self.pageFlowLayout.interitemSpacing = 10;
        self.pageFlowLayout.itemSize = CGSizeMake(60, 60);
        self.pageFlowLayout.pagingEnabled = YES;
        self.pageFlowLayout.pagingCellPosition = 0.5;
        self.pageFlowLayout.pagingBoundsPosition = 0.5;
        self.pageFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        self.collectionView = [[MKUICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.pageFlowLayout];
        self.collectionView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.collectionView.layer.borderWidth = 1;
        
        self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.showsVerticalScrollIndicator = NO;
        self.collectionView.model.forwardDelegate = self;
        [self.contentView addSubview:self.collectionView];
        //
        self.lineView = [[UIView alloc] init];
        self.lineView.backgroundColor = [UIColor systemRedColor];
        [self.contentView addSubview:self.lineView];
        
        @MK_WEAKIFY(self);
        MKUILayoutConstraintItemWrapper *w1 = [MKUILayoutConstraintItemWrapper wrapItem:self.collectionView sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
            @MK_NORMALIZE(self);
            return CGSizeMake(size.width, [self collectionViewHeight]);
        }];
        //
        self.pageControl = [[[self.class pageControlClass] alloc] init];
        [self.contentView addSubview:self.pageControl];
        
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[self.opertaionView,w1,self.pageControl] constraintParam:(MKUIFlowLayoutConstraintParam_V_T_C) contentInsets:MKUIEdgeInsetsMakeSameEdge(10) interitemSpacing:5];
        //
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.contentView.backgroundColor = [UIColor mk_colorWithLight:[UIColor whiteColor]];
        self.collectionView.backgroundColor = [UIColor mk_colorWithLight:[UIColor whiteColor]];
    }
    return self;
}
+ (Class)pageControlClass{
    return [TestUIPageControl class];
}
+ (Class)pageFlowLayoutClass{
    return [MKUICollectionViewPageFlowLayout class];
}
- (CGFloat)collectionViewHeight{
    return self.pageFlowLayout.itemSize.height+self.pageFlowLayout.sectionInset.top+self.pageFlowLayout.sectionInset.bottom;
}
- (NSInteger)scrollStep{
    return [self.cellModel mk_integerForKeyPath:@"step" otherwise:0];
}
- (void)setScrollStep:(NSInteger)step{
    self.cellModel[@"step"] = @(step);
    [self __refreshGripLayout];
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
    [self __refreshPageControl];
    [self layoutLineView];
}
- (void)layoutLineView{
    if(self.pageFlowLayout&&self.pageFlowLayout.pagingEnabled){
        MKCGAxis X = self.pageFlowLayout.scrollAxis;
        CGRect f1 = self.collectionView.frame;
        MKCGRectSetLength(&f1, X, 2);
        MKCGRectSetMin(&f1, X, MKCGRectGetMin(f1, X)+MKCGRectGetLength(self.collectionView.frame, X)*self.pageFlowLayout.pagingBoundsPositionForCollectionView);
        self.lineView.frame = f1;
    }
}
+ (Class)pageCellClass{
    return [MenuCollectionViewCell_OnePage class];
}
- (CGSize)customSizeThatFits:(CGSize)size{
    return [self.flowlayout sizeThatFits:size resizeItems:YES];
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    [self reloadData];
}
- (MenuCollectionViewCellModel *)gemMenuCM:(Menu *)menu{
    MenuCollectionViewCellModel *cm = [[MenuCollectionViewCellModel alloc] initWithModelObject:menu];
    cm.cellClass = [self.class pageCellClass];
    @MK_WEAKIFY(self);
    cm.whenClick = ^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
        @MK_NORMALIZE(self);
        @MK_WEAKIFY(self);
        [self.collectionView.model removeCellModel:cellModel animated:YES completion:^(BOOL finished) {
            @MK_NORMALIZE(self);
            [self __refreshPageControl];
        }];
    };
    return cm;
}
- (MenuCollectionViewCellModel *)gemAddMenuCM{
    MenuCollectionViewCellModel *cm = [[MenuCollectionViewCellModel alloc] initWithModelObject:[Menu addMenu]];
    cm.cellClass = [self.class pageCellClass];
    @MK_WEAKIFY(self);
    cm.whenClick = ^(__kindof MKUICollectionViewCellModel * _Nonnull cellModel) {
        @MK_NORMALIZE(self);
        MenuCollectionViewCellModel *cm = [self gemMenuCM:[Menu random]];
        NSIndexPath *indexpath = cellModel.indexPathInModel;
        [self.collectionView.model insertCellModel:cm atIndexPath:indexpath animated:YES completion:^(BOOL finished) {
            [self __refreshPageControl];
        }];
    };
    return cm;
}
- (void)reloadData{
    [self.collectionView.model removeAllSectionModels];
    NSArray<Menu *> *menus = self.cellModel.modelValue;
    for (Menu *menu in menus) {
        [self.collectionView.model addCellModel:[self gemMenuCM:menu]];
    }
    if(menus.count){
        [self.collectionView.model addCellModel:[self gemAddMenuCM]];
    }
    [self.collectionView.model reloadCollectionViewData];
    [self.collectionView layoutIfNeeded];
    [self __refreshGripLayout];
    [self __refreshPageControl];
    [self __refreshOperationView];
}
- (void)__refreshPageControl{
    self.pageControl.numberOfPages = self.collectionView.model.numberOfCells;
    self.pageControl.currentPage = self.pageFlowLayout.indexPathAtPagingCell.item;
}
- (void)__refreshOperationView{
    NSInteger step = self.scrollStep;
    BOOL pagingEnabled = [self.cellModel mk_boolForKeyPath:@"pagingEnabled" otherwise:YES];
    BOOL enableCycle = [self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
    self.opertaionView.stepLabel.text = [NSString stringWithFormat:@"Step:%@",@(step)];
    self.opertaionView.cycleButton.selected = enableCycle;
    self.pagingButton.selected = pagingEnabled;
    [self.opertaionView setNeedsLayout];
}
- (void)tableView:(UITableView *)tableView willDisplayCellModel:(__kindof MKUITableViewCellModel *)cellModel{
    [self __refreshGripLayout];
    [self __refreshPageControl];
    [self __refreshOperationView];
}
- (void)__refreshGripLayout{
    BOOL pagingEnabled = [self.cellModel mk_boolForKeyPath:@"pagingEnabled" otherwise:YES];
    BOOL enableCycle = [self.cellModel mk_boolForKeyPath:@"enableCycle" otherwise:YES];
    self.pageFlowLayout.enableCycleScroll = enableCycle;
    self.pageFlowLayout.pagingEnabled = pagingEnabled;
    NSIndexPath *currentPage = [self.cellModel mk_valueForKeyPath:@"currentPage"];
    if(currentPage){
        [self.pageFlowLayout setIndexPathAtPagingCell:currentPage animated:NO];
    }
    
    NSInteger step = self.scrollStep;
    BOOL autoScroll = step!=0;
    if(autoScroll){
        [self.pageFlowLayout startAutoScrollingWithDistance:step duration:2];
    }else{
        [self.pageFlowLayout stopAutoScrolling];
    }
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCellModel:(__kindof MKUITableViewCellModel *)cellModel{
    [self.pageFlowLayout stopAutoScrolling];
}

- (void)collectionView:(UICollectionView *)collectionView pageFlowLayout:(nonnull MKUICollectionViewPageFlowLayout *)collectionViewLayout didScrollToPagingCell:(nonnull NSIndexPath *)indexPathAtPagingCell{
    self.cellModel[@"currentPage"] = indexPathAtPagingCell;
    [self __refreshPageControl];
}
- (CGSize)collectionView:(UICollectionView *)collectionView pageFlowLayout:(MKUICollectionViewPageFlowLayout *)collectionViewLayout itemSizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGRect bounds = collectionView.bounds;
    bounds = UIEdgeInsetsInsetRect(bounds, MKUIEdgeInsetsMakeSameEdge(10));
    CGSize size = bounds.size;
    return size;
}
@end
